﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Tomahawk.Runtime.Logic.UI;
using Tomahawk.Runtime.Canvas.Sprite;
using Microsoft.Xna.Framework.Graphics;
using Tomahawk.Runtime.LoadingScreens;
using System.Threading;

namespace Tomahawk.Runtime.Timeline
{
    public abstract class SpriteEffectTrack : BaseTrack
    {
        #region Serializable Properties
        [XmlAttribute("EffectChannel")]
        public string channel;
        #endregion

        private SpriteEffect spriteEffect = null;

        public SpriteEffectTrack() 
        {
            spriteEffect = new SpriteEffect(GetEffectFile());
            spriteEffect.OnLoadEffectParameters += OnLoadEffectParameters;
        }

        public SpriteEffectTrack(string name)
            : base(name)
        {
            spriteEffect = new SpriteEffect(GetEffectFile());
            spriteEffect.OnLoadEffectParameters += OnLoadEffectParameters;
        }

        protected abstract string GetEffectFile();
        protected abstract void OnLoadEffectParameters(Effect effect);

        public override void OnPlayModeChanged(SyncGroup.PlayMode mode)
        {
            switch (mode)
            {
                case SyncGroup.PlayMode.Stop:
                    {
                        if (LoadingScreen.Working && Thread.CurrentThread != LoadingScreen.ActiveScreen.WorkerThread)
                        {
                            LoadingScreen.ActiveScreen.Canvas.UnregisterEffectFromChannel(spriteEffect, channel);
                        }
                        else
                        {
                            Engine.Instance.CanvasManager.UnregisterEffectFromChannel(spriteEffect, channel);
                        }
                    } break;

                case SyncGroup.PlayMode.PlayForward:
                case SyncGroup.PlayMode.PlayBackward:
                    {
                        if (LoadingScreen.Working && Thread.CurrentThread != LoadingScreen.ActiveScreen.WorkerThread)
                        {
                            LoadingScreen.ActiveScreen.Canvas.RegisterEffectToChannel(spriteEffect, channel);
                        }
                        else
                        {
                            Engine.Instance.CanvasManager.RegisterEffectToChannel(spriteEffect, channel);
                        }
                    } break;
            }
        }
    }
}
